package com.huineta.business.common.filter;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * FileName:     XssFilter
 * Author:       Dmm Lee< bclassline@gmail.com >
 * Date:         2022/12/5 14:37:02
 * Description:  Xss过滤器
 */
@WebFilter(filterName="XssFilter",urlPatterns= {"/*"})
@Component
public class XssFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
                         FilterChain filterChain) throws IOException, ServletException {
        //处理CORS问题
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        String url = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin", url);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Accept,Origin,Content-Type,LastModified,Cookie,UTOKEN");
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            response.setStatus(200, "success");
            response.flushBuffer();
            return;
        }
        //获取请求的url路径
        String path = ((HttpServletRequest) request).getServletPath();
        //声明要被忽略请求的数组
        String[] exclusionsUrls = {".js", ".gif", ".jpg", ".jpeg", ".png", ".css", ".ico", "health", "uploadPic", "file", "goods/create"};
        //请求参数不进行xss处理
        for (String str : exclusionsUrls) {
            if (path.contains(str)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        //对请求参数xss处理
        XssHttpServletRequestWrapper XssHttpServletRequestWrapper = new XssHttpServletRequestWrapper(request);
        filterChain.doFilter(XssHttpServletRequestWrapper, response);
    }

    @Override
    public void destroy() {

    }
}
